package com.happycat.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.happycat.mapper.GenerateIdMapper;
import com.happycat.mobile.service.GenerateIdService;
import com.happycat.utils.DateUtil;

@Service
public class GenerateIdServiceImpl implements GenerateIdService {

	@Autowired
	private GenerateIdMapper generateIdMapper;

	@Override
	public long nextSerialNumber(String sequenceName) {
		Long serialNumber = generateIdMapper.nextSerialNumber(sequenceName);
		String coveringSerialNumber = rightCoveringSerialNumber(serialNumber);
		String timeId = currentTimeId();
		String id = timeId+coveringSerialNumber;
		Long nextSerialNumber = Long.parseLong(id);
		return nextSerialNumber;
	}

	@Override
	public long userId() {
		Long serialNumber = generateIdMapper.nextSerialNumber("happycat_user_id");
		String coveringSerialNumber = rightCoveringSerialNumber(serialNumber);
		Long nextSerialNumber = Long.parseLong(coveringSerialNumber);
		return nextSerialNumber;
	}
	
	@Override
	public long nextDefaultSerialNumber() {
		Long serialNumber = generateIdMapper.nextSerialNumber("happycat_id");
		String coveringSerialNumber = rightCoveringSerialNumber(serialNumber);
		String timeId = currentTimeId();
		String id = timeId+coveringSerialNumber;
		Long nextSerialNumber = Long.parseLong(id);
		return nextSerialNumber;
	}
	public String currentTimeId() {
		String transid =  DateUtil.parseDateToStr(new Date(), DateUtil.DATE_FORMAT_YYYYMMDD)  ;
		return transid;

	}
	
	/**
	 * 
	 * @param serialNumber 左补齐
	 * @return 
	 */
	private String leftCoveringSerialNumber(Long serialNumber) {
		String s = serialNumber.toString();
		int len = s.length();
		if (len < 8) {
			for (int j = 0; j < 8 - len; j++) {
				s = "0" + s;
			}
		} else {
			s = s.substring(0, 7);
		}
		return s;
	}
	
	/**
	 * 
	 * @param serialNumber右补齐
	 * @return
	 */
	private  String rightCoveringSerialNumber(Long serialNumber) {
		String s = serialNumber.toString();
		int len = s.length();
		if (len < 8) {
			for (int j = 0; j < 8 - len; j++) {
				s = s+"0";
			}
		} else {
			s = s.substring(0, 7);
		}
		return s;
	}
	
}
